/* 
 * This file part of cget - A libcurl based downloading tool.
 * http://lianwei3.googlepages.com/home2
 * Copyright (C) 2006 Wei Lian <lianwei3@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "header.h"

bool file_exist(char *outfile)
{
    FILE *fp = fopen(outfile, "r");
    if (fp) {
	fclose(fp);
	return TRUE;
    } else
	return FALSE;
}

int min_value(int a, int b)
{
    return a < b ? a : b;
}

int max_value(int a, int b)
{
    return a >= b ? a : b;
}

int reallocate(std::vector < struct ThreadInfo >*vec_info,
	       uint begin, uint end, uint id, off_t max)
{
    int maxid = -1;
    for (uint i = begin; i < end; i++) {
	off_t remain = vec_info->at(i).end - vec_info->at(i).seek;
	if (remain > max) {
	    max = remain;
	    maxid = i;
	}
    }
    if (maxid != -1) {		///reallocate task 
	off_t mid = vec_info->at(maxid).end - max / 2;
	vec_info->at(id).end = vec_info->at(maxid).end;
	if (max >= 2)
	    vec_info->at(id).seek = mid + 1;
	else
	    vec_info->at(id).seek = mid;
	vec_info->at(maxid).end = mid;
    }
    return maxid;
}
